﻿Imports System.Data.SqlClient

Public Class frmApproveJournalVoucher

    Sub FillTempVouchersNo()
        Try
            Me.Cursor = Cursors.Default

            Dim cmd As New SqlCommand("Select Distinct MoveNo From TempTransactions Where TransType=N'Journal Voucher'", cnn)
            Dim Reader As SqlDataReader
            Dim X As Integer = 1

            Me.ListVouchers.Items.Clear()
            Me.GridVoucher.Rows.Clear()

            cnn.Open()
            Reader = cmd.ExecuteReader
            While Reader.Read
                Dim Item As New ListViewItem
                Item.Text = Reader.Item(0)
                Item.SubItems.Add(X)

                Me.ListVouchers.Items.Add(Item)
                X += 1
            End While
            cnn.Close()

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub FillBranches()
        Try
            Me.Cursor = Cursors.WaitCursor

            Me.CombBranch.Items.Clear()
            Dim Branches As ArrayList = GetBranches()

            For Each Branch As String In Branches
                Me.CombBranch.Items.Add(Branch)
            Next

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub frmApproveJournalVoucher_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.WindowState=FormWindowState.Maximized 

        FillBranches()
        FillTempVouchersNo()
    End Sub

    Private Sub ListVouchers_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListVouchers.SelectedIndexChanged
        Me.GridVoucher.Rows.Clear()

        If Me.ListVouchers.SelectedItems.Count > 0 Then
            Try
                Me.Cursor = Cursors.WaitCursor

                Dim cmd As New SqlCommand("Select * From TempTransactions Where MoveNo=" & Me.ListVouchers.SelectedItems(0).Text, cnn)
                Dim Reader As SqlDataReader

                Me.GridVoucher.Rows.Clear()

                cnn.Open()
                Reader = cmd.ExecuteReader
                While Reader.Read
                    Me.GridVoucher.Rows.Add(New String() {Reader.Item("AccNo"), Reader.Item("Acc1"), Reader.Item("Acc2"), Reader.Item("Acc3"), _
                                                          Reader.Item("Acc4"), "Search...", Reader.Item("Descr"), Reader.Item("ChNo"), _
                                                          Reader.Item("Branch"), CDbl(Reader.Item("TotalOut")).ToString("N2"), _
                                                          CDbl(Reader.Item("TotalIn")).ToString("N2"), "Delete"})
                    Me.DTPTrans.Value = CDate(Reader.Item("TransDate"))
                End While
                cnn.Close()

                Calculate()

                Me.Cursor = Cursors.Default
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                If cnn.State = ConnectionState.Open Then
                    cnn.Close()
                End If
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        FillTempVouchersNo()
    End Sub

    Private Sub ChAccPath_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChAccPath.CheckedChanged
        If Me.ChAccPath.Checked = True Then
            Me.Acc1.Visible = True
            Me.Acc2.Visible = True
            Me.Acc3.Visible = True
        ElseIf Me.ChAccPath.Checked = False Then
            Me.Acc1.Visible = False
            Me.Acc2.Visible = False
            Me.Acc3.Visible = False
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnApprove.Click
        Me.ErrProv.Clear()
        If Me.GridVoucher.Rows.Count = 0 Then
            Exit Sub
        ElseIf CDbl(Me.txtCrd.Text - Me.txtDep.Text) <> 0 Then
            Me.ErrProv.SetError(Me.txtBalance, "Please complete the voucher")
            Exit Sub
        ElseIf ValidateDate(Me.DTPTrans.Value) = False Then
            Me.ErrProv.SetError(Me.DTPTrans, "Date isn't accepted")
        Else
            Try
                Me.Cursor = Cursors.WaitCursor

                'Validate rows
                Dim Valid As Boolean = True
                For Each row As DataGridViewRow In Me.GridVoucher.Rows
                    If row.Index <> (Me.GridVoucher.Rows.Count - 1) Then
                        If row.Cells(4).Style.BackColor = Color.Salmon OrElse row.Cells(6).Value = "" _
                      OrElse row.Cells(7).Value = "" OrElse row.Cells(8).Value = "" OrElse row.Cells(9).Style.BackColor = Color.Salmon Then
                            row.ErrorText = "Please fill in all fields"
                            Valid = False
                        Else
                            row.ErrorText = ""
                        End If
                    End If
                Next

                If Valid = False Then
                    Me.Cursor = Cursors.Default
                    Exit Sub
                End If

                Dim MoveNo As Integer
                Dim cmd As New SqlCommand
                Dim Trans As SqlTransaction
                Dim SavedUser As String

                cnn.Open()
                cmd.Connection = cnn
                Trans = cnn.BeginTransaction
                cmd.Transaction = Trans

                'Get SavedUser
                cmd.CommandText = "Select SavedUser From TempTransactions Where MoveNo=" & Me.ListVouchers.SelectedItems(0).Text
                SavedUser = cmd.ExecuteScalar

                'Get Move No.
                cmd.CommandText = "Select IsNull(Max(MoveNo),0) From Transactions Where Branch=N'" & Branch & "' and Year(TransDate)=" & Me.DTPTrans.Value.Year
                MoveNo = CInt(cmd.ExecuteScalar) + 1

                For Each row As DataGridViewRow In Me.GridVoucher.Rows
                    If row.Index <> (Me.GridVoucher.Rows.Count - 1) Then
                        cmd.CommandText = "Insert into Transactions (TransType,MoveNo,AccNo,Acc1,Acc2,Acc3,Acc4,Descr,ChNo,TotalOut,TotalIn," & _
                                          "SavedUser,TransDate,Branch,ApprovedUser,ApprovedDate) Values (@TransType,@MoveNo,@AccNo,@Acc1," & _
                                          "@Acc2,@Acc3,@Acc4,@Descr,@ChNo,@TotalOut,@TotalIn,@SavedUser,@TransDate,@Branch,@ApprovedUser,GetDate())"

                        cmd.Parameters.Clear()
                        cmd.Parameters.AddWithValue("@TransType", "Journal Voucher")
                        cmd.Parameters.AddWithValue("@MoveNo", MoveNo)
                        cmd.Parameters.AddWithValue("@AccNo", row.Cells(0).Value)
                        cmd.Parameters.AddWithValue("@Acc1", row.Cells(1).Value)
                        cmd.Parameters.AddWithValue("@Acc2", row.Cells(2).Value)
                        cmd.Parameters.AddWithValue("@Acc3", row.Cells(3).Value)
                        cmd.Parameters.AddWithValue("@Acc4", row.Cells(4).Value)
                        cmd.Parameters.AddWithValue("@Descr", row.Cells(6).Value)
                        cmd.Parameters.AddWithValue("@ChNo", row.Cells(7).Value)
                        cmd.Parameters.AddWithValue("@Branch", row.Cells(8).Value)
                        cmd.Parameters.AddWithValue("@TotalOut", CDbl(row.Cells(9).Value))
                        cmd.Parameters.AddWithValue("@TotalIn", CDbl(row.Cells(10).Value))
                        cmd.Parameters.AddWithValue("@SavedUser", SavedUser)
                        cmd.Parameters.AddWithValue("@TransDate", Me.DTPTrans.Value)
                        cmd.Parameters.AddWithValue("@ApprovedUser", CurrentUser)
                        cmd.ExecuteNonQuery()
                    End If
                Next

                'Delete from Temp. Vouchers
                cmd.CommandText = "Delete From TempTransactions Where MoveNo=" & Me.ListVouchers.SelectedItems(0).Text
                cmd.ExecuteNonQuery()

                Trans.Commit()
                cnn.Close()

                MsgBox("Approved Successfully")

                'PrintVoucher(MoveNo, Me.DTPTrans.Value.Year)
                'FillTempVouchersNo()

                Clear()

                Me.Cursor = Cursors.Default
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                MsgBox(ex.ToString)
                If cnn.State = ConnectionState.Open Then
                    cnn.Close()
                End If
            End Try
        End If
    End Sub

    Sub Calculate()
        If Me.GridVoucher.Rows.Count = 0 Then
            Me.txtCrd.Text = "0"
            Me.txtDep.Text = "0"
            Me.txtBalance.Text = "0"
        Else
            Try
                Dim Crd, Dep As Double
                Dim i As Integer

                ' Iterate through a dictionary
                For i = 0 To Me.GridVoucher.Rows.Count - 1
                    Dep = Dep + Me.GridVoucher.Rows(i).Cells(9).Value
                    Crd = Crd + Me.GridVoucher.Rows(i).Cells(10).Value
                Next

                If Crd = 0 Then
                    Me.txtCrd.Text = "0.00"
                Else
                    Me.txtCrd.Text = Format(Crd, "##,###.##")
                End If

                If Dep = 0 Then
                    Me.txtDep.Text = "0.00"
                Else
                    Me.txtDep.Text = Format(Dep, "##,###.##")
                End If

                If Crd - Dep = 0 Then
                    Me.txtBalance.Text = "0.00"
                Else
                    Me.txtBalance.Text = Format(CDbl(Crd - Dep), "##,###.##")
                End If
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub

    Sub Clear()
        Me.GridVoucher.Rows.Clear()
        Me.txtCrd.Text = "0.00"
        Me.txtDep.Text = "0.00"
        Me.txtBalance.Text = "0.00"
        Me.GridVoucher.Focus()
    End Sub


    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        If Me.ListVouchers.SelectedItems.Count > 0 Then
            Try
                If MsgBox("Confirm deleting?", MsgBoxStyle.YesNoCancel) = MsgBoxResult.Yes Then
                    Me.Cursor = Cursors.WaitCursor

                    Dim cmd As New SqlCommand("Delete From TempTransactions where MoveNo=" & Me.ListVouchers.SelectedItems(0).Text, cnn)

                    cnn.Open()
                    cmd.ExecuteNonQuery()
                    cnn.Close()

                    FillTempVouchersNo()

                    Me.Cursor = Cursors.Default
                End If
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                If cnn.State = ConnectionState.Open Then
                    cnn.Close()
                End If
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        Clear()
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub


    Private Sub GridVoucher_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridVoucher.CellClick
        If e.ColumnIndex = 5 Then
            Try
                Dim a As New frmSelectAccount
                a.ShowDialog()

                If SelAccNo <> "" Then
                    Me.Cursor = Cursors.WaitCursor

                    'Get acc path
                    Dim AccNames(3) As String
                    AccNames = GetAccNames(SelAccNo)

                    Me.GridVoucher.CurrentRow.Cells(0).Value = SelAccNo
                    Me.GridVoucher.CurrentRow.Cells(1).Value = AccNames(0)
                    Me.GridVoucher.CurrentRow.Cells(2).Value = AccNames(1)
                    Me.GridVoucher.CurrentRow.Cells(3).Value = AccNames(2)
                    Me.GridVoucher.CurrentRow.Cells(4).Value = AccNames(3)

                    Me.Cursor = Cursors.Default
                End If
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                MsgBox(ex.ToString)
            End Try
        ElseIf e.ColumnIndex = 11 Then
            If e.RowIndex < (Me.GridVoucher.Rows.Count - 1) Then
                Me.GridVoucher.Rows.RemoveAt(e.RowIndex)
            End If
        End If
    End Sub

    Private Sub GridVoucher_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridVoucher.CellEndEdit
        If e.ColumnIndex = 0 Then
            Try
                If Me.GridVoucher.CurrentCell.Value <> "" Then
                    Me.Cursor = Cursors.WaitCursor

                    'Get acc path
                    Dim AccNames(3) As String
                    AccNames = GetAccNames(Me.GridVoucher.CurrentCell.Value)

                    Me.GridVoucher.CurrentRow.Cells(1).Value = AccNames(0)
                    Me.GridVoucher.CurrentRow.Cells(2).Value = AccNames(1)
                    Me.GridVoucher.CurrentRow.Cells(3).Value = AccNames(2)
                    Me.GridVoucher.CurrentRow.Cells(4).Value = AccNames(3)

                    Me.Cursor = Cursors.Default
                Else
                    Me.GridVoucher.CurrentRow.Cells(1).Value = ""
                    Me.GridVoucher.CurrentRow.Cells(2).Value = ""
                    Me.GridVoucher.CurrentRow.Cells(3).Value = ""
                    Me.GridVoucher.CurrentRow.Cells(4).Value = ""
                End If
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                MsgBox(ex.ToString)
            End Try

        ElseIf e.ColumnIndex = 9 Then
            If Me.GridVoucher.CurrentCell.Value = "" Then
                Me.GridVoucher.CurrentCell.Value = "0.00"
            Else
                Try
                    Me.GridVoucher.CurrentCell.Value = CDbl(Me.GridVoucher.CurrentCell.Value).ToString("N2")
                    If CDbl(Me.GridVoucher.CurrentCell.Value) <> 0 Then
                        Me.GridVoucher.CurrentRow.Cells(10).Value = "0.00"
                    End If
                Catch ex As Exception
                    Me.GridVoucher.CurrentCell.Value = "0.00"
                End Try
            End If

        ElseIf e.ColumnIndex = 10 Then
            If Me.GridVoucher.CurrentCell.Value = "" Then
                Me.GridVoucher.CurrentCell.Value = "0.00"
            Else
                Try
                    Me.GridVoucher.CurrentCell.Value = CDbl(Me.GridVoucher.CurrentCell.Value).ToString("N2")
                    If CDbl(Me.GridVoucher.CurrentCell.Value) <> 0 Then
                        Me.GridVoucher.CurrentRow.Cells(9).Value = "0.00"
                    End If
                Catch ex As Exception
                    Me.GridVoucher.CurrentCell.Value = "0.00"
                End Try
            End If

        End If

        Calculate()
        ValidateGrid()
    End Sub

    Private Sub GridVoucher_RowsRemoved(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles GridVoucher.RowsRemoved
        Calculate()
        ValidateGrid()
    End Sub

    Sub ValidateGrid()
        Try
            Me.Cursor = Cursors.WaitCursor

            For Each row As DataGridViewRow In Me.GridVoucher.Rows
                If row.Cells(4).Value = "" Then
                    row.Cells(4).Style.BackColor = Color.Salmon
                Else
                    row.Cells(4).Style.BackColor = row.DefaultCellStyle.BackColor
                End If

                If CDbl(row.Cells(9).Value) = 0 And CDbl(row.Cells(10).Value) = 0 Then
                    row.Cells(9).Style.BackColor = Color.Salmon
                    row.Cells(10).Style.BackColor = Color.Salmon

                ElseIf CDbl(row.Cells(9).Value) = 0 Or CDbl(row.Cells(10).Value) = 0 Then
                    row.Cells(9).Style.BackColor = row.DefaultCellStyle.BackColor
                    row.Cells(10).Style.BackColor = row.DefaultCellStyle.BackColor
                End If
            Next

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
        End Try
    End Sub
End Class